package com.circle.search;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.circle.search.model.EsResult;

public class DBconnD {
	public static TransportClient client;
	public final static String sqlSearch="select * from es_static limit 10";
	public final static String sqlUpdate="update es_static set uid='%s', amount=%s where passport = '%s'";
	
	private DruidDataSource dds = null;
	
	public void initDruidDataSourceFactory(){
		try {
			dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(DBconfig.getProperties());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public DruidDataSource getDruidDataSource(){
		return dds;
	}
	
	//test
	public static void main(String[] args) {
		Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "uc_es").build();
		client = new TransportClient(settings);
		DruidPooledConnection dpc = null;
	    Statement stmt = null;
	    ResultSet rset = null;
	    int rset2 = 0;
		try {
			DBconnD dbd = new DBconnD();
			dbd.initDruidDataSourceFactory();
			dpc = dbd.getDruidDataSource().getConnection();
            stmt = dpc.createStatement();
            System.out.println("Executing statement.");
            rset = stmt.executeQuery("select * from es_static");//该数据库中有 users 表
            System.out.println("Results:");
            int numcols = rset.getMetaData().getColumnCount();
            
            while(rset.next()) {
            	String passport = rset.getString(2);
            	EsResult esResult = EsSearch.searchEsByPassport(passport, client);
        		System.out.println(passport + " 对应的uid:" + esResult.getUid() + " 数量：" + esResult.getUidCount());
            	String sql = String.format(sqlUpdate, esResult.getUid(), esResult.getUidCount(), passport);
            	PreparedStatement preStatement = dpc.prepareStatement(sql);
            	
            	rset2 = preStatement.executeUpdate(sql);
            	try { if (preStatement != null) preStatement.close(); } catch(Exception e) { }
            }
            
//            while(rset.next()) {
//                for(int i=1;i<=numcols;i++) {
//                    System.out.print("\t" + rset.getString(i));
//                }
//                System.out.println("");
//            }
            
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
            try { if (rset != null) rset.close(); } catch(Exception e) { }
            try { if (stmt != null) stmt.close(); } catch(Exception e) { }
            try { if (dpc != null) dpc.close(); } catch(Exception e) { }
        }
	}
	
}